package com.zxt.redis.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
    private static RedisTemplate redisTemplate;
    public static final String REDIS_PREFIX = "zxt:";

    public RedisUtil() {
    }

    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisUtil.redisTemplate = redisTemplate;
    }

    private static String getRealKey(String key) {
        return !key.contains(REDIS_PREFIX) ? REDIS_PREFIX + key : key;
    }

    public static Object get(String key) {
        return StringUtils.isEmpty(key) ? null : redisTemplate.opsForValue().get(getRealKey(key));
    }

    public static void set(String key, Object value, TimeUnit unit, long timeout) {
        if (!StringUtils.isEmpty(key)) {
            key = getRealKey(key);
            redisTemplate.opsForValue().set(key, value, timeout, unit);
        }
    }

    public static void expire(String key, TimeUnit unit, long timeout) {
        if (!StringUtils.isEmpty(key)) {
            key = getRealKey(key);
            redisTemplate.expire(key, timeout, unit);
        }
    }

    public static void delete(String key) {
        if (!StringUtils.isEmpty(key)) {
            key = getRealKey(key);
            redisTemplate.delete(key);
        }
    }
}
